// src/components/sidebar/SidebarMenu.tsx

import { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { FaBuilding, FaUserGraduate, FaDownload } from 'react-icons/fa';
import ScholarsReportDownloadConfirmModal from '@/components/popups/reportsDownload/scholarsReport/ScholarsReportDownloadConfirmModal';
import SponsorsReportDownloadConfirmModal from '@/components/popups/reportsDownload/sponsorsReport/SponsorsReportDownloadConfirmModal';
import { exportScholarPerformanceReport } from '@/services/scholarsDashboardService/scholarPerformanceReport';
import { exportSponsorCommitmentReport } from '@/services/sponsorDashboardService/sponsorCommitReport';
import { usePermissions } from '@/utils/permissionUtils';

interface MenuItem {
  key: string;
  label: string;
  icon: React.ReactElement;
  path: string | null;
  active: boolean;
  isDownload?: boolean;
  onClick?: () => void;
  disabled?: boolean;
}

const SidebarMenu = ({ collapsed = false, mobile = false }: { collapsed?: boolean; mobile?: boolean }) => {
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const {
    canViewScholarsReports,
    canExportScholarsReports,
    canViewSponsorsReports,
    canExportSponsorsReports
  } = usePermissions();

  const [isScholarsModalOpen, setScholarsModalOpen] = useState(false);
  const [isSponsorsModalOpen, setSponsorsModalOpen] = useState(false);
  const [downloading, setDownloading] = useState(false);

  const canDownloadScholars = canViewScholarsReports && canExportScholarsReports;
  const canDownloadSponsors = canViewSponsorsReports && canExportSponsorsReports;

  const handleScholarsDownloadClick = () => {
    if (!canDownloadScholars) return;
    setScholarsModalOpen(true);
  };

  const handleSponsorsDownloadClick = () => {
    if (!canDownloadSponsors) return;
    setSponsorsModalOpen(true);
  };

  const handleScholarsConfirm = async (code: string) => {
    setScholarsModalOpen(false);
    setDownloading(true);
    try {
      const blob = await exportScholarPerformanceReport(code);
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `scholar_performance_report_${code}.xlsx`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
    } catch (err) {
      alert('Download failed: ' + (err instanceof Error ? err.message : err));
    } finally {
      setDownloading(false);
    }
  };

  const handleSponsorsConfirm = async (code: string) => {
    setSponsorsModalOpen(false);
    setDownloading(true);
    try {
      const blob = await exportSponsorCommitmentReport(code);
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `sponsor_commitment_report_${code}.xlsx`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
    } catch (err) {
      alert('Download failed: ' + (err instanceof Error ? err.message : err));
    } finally {
      setDownloading(false);
    }
  };

  const handleScholarsCancel = () => {
    setScholarsModalOpen(false);
  };

  const handleSponsorsCancel = () => {
    setSponsorsModalOpen(false);
  };

  const menuItems: MenuItem[] = [
    {
      key: 'sponsor',
      label: 'Sponsors Dashboard',
      icon: <FaBuilding />,
      path: '/sponsors',
      active: pathname.includes('sponsor'),
    },
    {
      key: 'scholar',
      label: 'Scholars Dashboard',
      icon: <FaUserGraduate />,
      path: '/scholars',
      active: pathname.includes('scholar'),
    },
  ];

  const mobileMenuItems: MenuItem[] = mobile ? [
    ...menuItems,
    ...(pathname.includes('scholar') ? [{
      key: 'scholar-download',
      label: 'Download Report',
      icon: <FaDownload />,
      path: null,
      active: false,
      isDownload: true,
      onClick: handleScholarsDownloadClick,
      disabled: downloading || !canDownloadScholars,
    }] : []),
    ...(pathname.includes('sponsor') ? [{
      key: 'sponsor-download',
      label: 'Download Report',
      icon: <FaDownload />,
      path: null,
      active: false,
      isDownload: true,
      onClick: handleSponsorsDownloadClick,
      disabled: downloading || !canDownloadSponsors,
    }] : []),
  ] : menuItems;

  return (
    <>
      <div className={`font-medium ${mobile ? 'flex flex-row w-full justify-around items-center text-base py-1 gap-0.5 bg-white dark:bg-slate-900' : 'flex flex-col text-lg text-gray-700 dark:text-gray-200 px-3 py-4'} transition-all duration-300`}>
        {/* Main menu items */}
        <ul className={`${mobile ? 'flex flex-row w-full justify-around items-center' : 'flex flex-col'} w-full`}>
          {(mobile ? mobileMenuItems : menuItems).map((item) => (
            <li
              key={item.key}
              className={`flex items-center ${mobile ? 'justify-center flex-1' : 'gap-3 mb-2'} px-0 py-0`}
            >
              <button
                onClick={item.isDownload ? item.onClick : () => item.path && navigate(item.path)}
                aria-label={item.label}
                disabled={item.disabled}
                className={`flex items-center w-full rounded-xl transition-all duration-200 ease-in-out
                  ${item.active
                    ? 'bg-gradient-to-r from-blue-600 to-cyan-500 text-white shadow-lg font-bold border-2 border-blue-400 dark:from-blue-700 dark:to-cyan-700 dark:border-cyan-700'
                    : item.isDownload && item.disabled
                      ? 'bg-gray-100 dark:bg-slate-700 text-gray-400 dark:text-gray-500 border border-gray-200 dark:border-slate-600 cursor-not-allowed opacity-50'
                      : 'bg-white dark:bg-slate-800 text-gray-700 dark:text-gray-200 hover:bg-blue-50 dark:hover:bg-slate-700 hover:text-blue-700 dark:hover:text-cyan-300 border border-transparent hover:border-blue-200 dark:hover:border-cyan-700'}
                  ${mobile ? 'justify-center text-xl shadow-sm py-1.5 px-1.5' : 'gap-4 px-4 py-3 text-lg font-medium'}
                  focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-1
                  group
                `}
                type="button"
                title={item.isDownload ? (downloading ? 'Downloading...' : 'Download Report') : item.label}
              >
                <span className={`transition-all duration-200 ${mobile ? 'text-xl' : 'text-2xl'} ${item.active ? 'text-white drop-shadow' : item.isDownload && item.disabled ? 'text-gray-400 dark:text-gray-500' : 'text-blue-400 dark:text-cyan-400 group-hover:text-blue-600 dark:group-hover:text-cyan-300'}`}>
                  {item.isDownload && downloading ? (
                    <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                  ) : (
                    item.icon
                  )}
                </span>
                {!collapsed && !mobile && (
                  <span className={`ml-1 whitespace-nowrap text-base transition-all duration-200 ${item.active ? 'text-white font-bold' : item.isDownload && item.disabled ? 'text-gray-400 dark:text-gray-500' : 'text-gray-800 dark:text-gray-200 group-hover:text-blue-700 dark:group-hover:text-cyan-300'}`}>
                    {item.isDownload && downloading ? 'Downloading...' : item.label}
                  </span>
                )}
              </button>
            </li>
          ))}
        </ul>

        {/* Download buttons section - Desktop only */}
        {!mobile && (
          <div className="mt-4 pt-4 border-t border-gray-200 dark:border-slate-700">
            {/* Download button for Scholars Dashboard */}
            {pathname.includes('scholar') && (
              <div className="mb-2">
                <button
                  onClick={handleScholarsDownloadClick}
                  aria-label="Download Scholar Performance Report"
                  disabled={downloading || !canDownloadScholars}
                  className={`flex items-center w-full rounded-xl transition-all duration-200 ease-in-out
                    ${canDownloadScholars
                      ? 'bg-white dark:bg-slate-800 text-gray-700 dark:text-gray-200 hover:bg-blue-50 dark:hover:bg-slate-700 hover:text-blue-700 dark:hover:text-cyan-300 border border-transparent hover:border-blue-200 dark:hover:border-cyan-700'
                      : 'bg-gray-100 dark:bg-slate-700 text-gray-400 dark:text-gray-500 border border-gray-200 dark:border-slate-600 cursor-not-allowed opacity-50'}
                    gap-4 px-4 py-3 text-lg font-medium
                    focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-1
                    group
                  `}
                  type="button"
                  title={!canDownloadScholars ? 'You need View & Export permission to download reports' : 'Download Scholar Performance Report'}
                >
                  <span className={`transition-all duration-200 text-2xl ${canDownloadScholars ? 'text-blue-400 dark:text-cyan-400 group-hover:text-blue-600 dark:group-hover:text-cyan-300' : 'text-gray-400 dark:text-gray-500'}`}>
                    {downloading ? (
                      <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                    ) : (
                      <FaDownload />
                    )}
                  </span>
                  {!collapsed && (
                    <span className={`ml-1 whitespace-nowrap text-base transition-all duration-200 ${canDownloadScholars ? 'text-gray-800 dark:text-gray-200 group-hover:text-blue-700 dark:group-hover:text-cyan-300' : 'text-gray-400 dark:text-gray-500'}`}>
                      {downloading ? 'Downloading...' : 'Scholars Report'}
                    </span>
                  )}
                </button>
              </div>
            )}

            {/* Download button for Sponsors Dashboard */}
            {pathname.includes('sponsor') && (
              <div className="mb-2">
                <button
                  onClick={handleSponsorsDownloadClick}
                  aria-label="Download Sponsor Commitment Report"
                  disabled={downloading || !canDownloadSponsors}
                  className={`flex items-center w-full rounded-xl transition-all duration-200 ease-in-out
                    ${canDownloadSponsors
                      ? 'bg-white dark:bg-slate-800 text-gray-700 dark:text-gray-200 hover:bg-blue-50 dark:hover:bg-slate-700 hover:text-blue-700 dark:hover:text-cyan-300 border border-transparent hover:border-blue-200 dark:hover:border-cyan-700'
                      : 'bg-gray-100 dark:bg-slate-700 text-gray-400 dark:text-gray-500 border border-gray-200 dark:border-slate-600 cursor-not-allowed opacity-50'}
                    gap-4 px-4 py-3 text-lg font-medium
                    focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-1
                    group
                  `}
                  type="button"
                  title={!canDownloadSponsors ? 'You need View & Export permission to download reports' : 'Download Sponsor Commitment Report'}
                >
                  <span className={`transition-all duration-200 text-2xl ${canDownloadSponsors ? 'text-blue-400 dark:text-cyan-400 group-hover:text-blue-600 dark:group-hover:text-cyan-300' : 'text-gray-400 dark:text-gray-500'}`}>
                    {downloading ? (
                      <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                    ) : (
                      <FaDownload />
                    )}
                  </span>
                  {!collapsed && (
                    <span className={`ml-1 whitespace-nowrap text-base transition-all duration-200 ${canDownloadSponsors ? 'text-gray-800 dark:text-gray-200 group-hover:text-blue-700 dark:group-hover:text-cyan-300' : 'text-gray-400 dark:text-gray-500'}`}>
                      {downloading ? 'Downloading...' : 'Sponsors Report'}
                    </span>
                  )}
                </button>
              </div>
            )}
          </div>
        )}

        {/* Download Modals */}
        <ScholarsReportDownloadConfirmModal
          isOpen={isScholarsModalOpen}
          onConfirm={handleScholarsConfirm}
          onCancel={handleScholarsCancel}
          loading={downloading}
        />
        <SponsorsReportDownloadConfirmModal
          isOpen={isSponsorsModalOpen}
          onConfirm={handleSponsorsConfirm}
          onCancel={handleSponsorsCancel}
          loading={downloading}
        />
      </div>
    </>
  );
};

export default SidebarMenu;